package com.zhuqiandann.scis.controller;

import com.jcohy.date.DateUtils;
import com.zhuqiandann.scis.common.JsonResult;
import com.zhuqiandann.scis.common.PageJson;
import com.zhuqiandann.scis.model.Answer;
import com.zhuqiandann.scis.model.Notice;
import com.zhuqiandann.scis.service.AnswerService;
import com.zhuqiandann.scis.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin/answer")
public class AdminAnswerController extends BaseController{
    @Autowired
    AnswerService answerService;
    @Autowired
    NoticeService noticeService;

    @GetMapping("/list")
    @ResponseBody
    public PageJson<Answer> all(ModelMap map){
        List<Answer> paperList = answerService.findAll();
        PageJson<Answer> page = new PageJson<>();
        page.setCode(0);
        page.setMsg("成功");
        page.setCount(paperList.size());
        page.setData(paperList);
        return page;
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(Answer answer){
        try {
            answerService.saveOrUpdate(answer);
            Notice notice = new Notice();
            notice.setDate(DateUtils.getCurrentDateStr());
            notice.setStudentNum(answer.getNum());
            notice.setContent("学生"+answer.getNum()+",在"+answer.getPaper().getTitle()+"进行了问卷填写");
            notice.setStatus("1");
            notice.setLevel(2);
            noticeService.save(notice);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.ok();
    }

    @DeleteMapping("{id}/del")
    @ResponseBody
    public JsonResult del(@PathVariable("id") Integer id){
        try {
            answerService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail("删除失败");
        }
        return JsonResult.ok();
    }
}